package kingiis.utils.simpleapp.anno;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.util.Log;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by King on 2017/12/29 0029.
 */
public class Anno {
    public static void bind(Activity activity) {
        view(activity);
        vertical(activity);
    }


    //setContentView
    public static void view(Activity activity) {
        Log.i("tag", "1");
        Class a = activity.getClass();
        if (a.isAnnotationPresent(Layout.class)) {
            // View
            Layout contentLayout =
                    (Layout) a.getAnnotation(Layout.class);
            // 得到注解的值
            int layoutId = contentLayout.value();
            // 使用反射调用setContentView
            try {
                Method method = a.getMethod("setContentView", int.class);
                method.setAccessible(true);
                method.invoke(activity, layoutId);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }


    // findViewById
    public static void vertical(Activity activity) {
        Class a = activity.getClass();
        // 得到activity所有字段
        Field[] fields = a.getDeclaredFields();
        // 得到被ViewInject注解的字段
        for (Field field : fields) {
            try {
                // 使用反射调用setRequestedOrientation，并为字段设置值
                Method method = a.getMethod("setRequestedOrientation", int.class);
                method.setAccessible(true);
                Object resView = method.invoke(activity, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//                Object resView = method.invoke(activity, ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
                field.setAccessible(true);
                field.set(activity, resView);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

}
